package com.kintreda.service.config;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.kintreda.common.config.exception.CommonBaseErrorCode;
import com.kintreda.tools.CommonUtils;
import com.kintreda.tools.utils.AesUtils;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

@Component
@Data
public class GlobalInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //验证客户端访问合法性
        String sign = request.getHeader("sign");
        if (StringUtils.isNoneBlank(sign)){
            String time = AesUtils.aesDecrypt(sign, null);
            try {
                String timeStr = CommonUtils.stampToTime(time);
                //签名有效期为1分钟
                LocalDateTime dateTime = LocalDateTimeUtil.parse(timeStr, "yyyy-MM-dd HH:mm:ss").plusMinutes(1);
                if (dateTime.isAfter(LocalDateTime.now())){
                    return true;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", CommonBaseErrorCode.NOT_AUTH.getCode());
        jsonObject.put("message", CommonBaseErrorCode.NOT_AUTH.getErrMsg());

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(jsonObject);
        return false;
    }
}
